// pages/group-detail/group-detail.ts
import { getPublishDetail, participatePublish, quitPublish } from '../../../api/publish';
import { formatSpecification } from '../../../utils/util';

Page({
  data: {
    id: 0,
    detail: null as any,
    loading: true,
    isFavorite: false,
    isParticipated: false, // 是否已参与
    isOwner: false, // 是否是创建者
    submitting: false, // 提交中
  },

  onLoad(options: any) {
    if (options.id) {
      this.setData({ id: parseInt(options.id) });
      this.loadDetail();
    }
  },

  // 加载详情
  async loadDetail() {
    this.setData({ loading: true });

    try {
      const res = await getPublishDetail(this.data.id);
      
      if (res.status === 200 && res.data) {
        // 格式化规格信息
        const formattedDetail = {
          ...res.data,
          spec: formatSpecification(res.data.spec || '')
        };
        
        // 格式化参与者时间
        if (formattedDetail.participants && formattedDetail.participants.length > 0) {
          formattedDetail.participants = formattedDetail.participants.map((participant: any) => {
            return {
              ...participant,
              add_time: this.formatTime(participant.add_time),
              avatar_name: this.getAvatarName(participant.user)
            };
          });
        }
        
        this.setData({ detail: formattedDetail });
      }
    } catch (error: any) {
      console.error('加载详情失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '加载失败'),
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 获取头像名称
  getAvatarName(user: any) {
    if (!user) return '匿';
    
    // 优先使用real_name，其次nickname
    const name = user.real_name || user.nickname;
    if (!name || name === 'null' || name.length === 0) {
      return '匿';
    }
    
    return name.charAt(0);
  },

  // 格式化时间
  formatTime(timeStr: string) {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    // 计算时间差
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 1) {
      return '刚刚';
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      // 超过7天显示具体日期
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      
      if (year === now.getFullYear()) {
        return `${month}-${day} ${hour}:${minute}`;
      } else {
        return `${year}-${month}-${day} ${hour}:${minute}`;
      }
    }
  },

  // 切换收藏
  toggleFavorite() {
    this.setData({
      isFavorite: !this.data.isFavorite
    });
    wx.showToast({
      title: this.data.isFavorite ? '收藏成功' : '取消收藏',
      icon: 'success'
    });
  },

  // 举报
  reportGroup() {
    wx.showActionSheet({
      itemList: ['虚假信息', '价格欺诈', '侵犯版权', '违法内容', '其他'],
      success: () => {
        wx.showModal({
          title: '确认举报',
          content: `确定要举报该拼单吗？`,
          success: (modalRes) => {
            if (modalRes.confirm) {
              wx.showToast({
                title: '举报已提交',
                icon: 'success'
              });
            }
          }
        });
      }
    });
  },

  // 联系发起人
  contactInitiator() {
    if (this.data.detail) {
      wx.showModal({
        title: '联系发起人',
        content: `联系人：${this.data.detail.contact_name}\n电话：${this.data.detail.contact_phone}`,
        showCancel: true,
        confirmText: '拨打电话',
        success: (res) => {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: this.data.detail.contact_phone
            });
          }
        }
      });
    }
  },

  // 参与拼单
  async joinGroup() {
    if (this.data.submitting) return;

    // 检查是否已参与
    if (this.data.isParticipated) {
      wx.showToast({
        title: '您已参与该拼单',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '提示',
      content: '确定要参与这个拼单吗？',
      success: async (res) => {
        if (res.confirm) {
          this.setData({ submitting: true });
          
          try {
            const result = await participatePublish(this.data.id);
            
            if (result.status === 200 || result.code === 200) {
              this.setData({ isParticipated: true });
              wx.showToast({
                title: '参与成功',
                icon: 'success'
              });
              // 重新加载详情以获取最新参与状态
              this.loadDetail();
            } else {
              wx.showToast({
                title: result.msg || '参与失败',
                icon: 'none'
              });
            }
          } catch (error: any) {
            console.error('参与拼单失败:', error);
            wx.showToast({
              title: typeof(error) === 'string' ? error : (error?.msg || '参与失败，请重试'),
              icon: 'none'
            });
          } finally {
            this.setData({ submitting: false });
          }
        }
      }
    });
  },

  // 退出拼单
  async quitGroup() {
    if (this.data.submitting) return;

    // 检查是否是创建者
    if (this.data.isOwner) {
      wx.showToast({
        title: '拼单创建者不能退出',
        icon: 'none'
      });
      return;
    }

    // 检查是否已参与
    if (!this.data.isParticipated) {
      wx.showToast({
        title: '您还未参与该拼单',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '提示',
      content: '确定要退出这个拼单吗？',
      success: async (res) => {
        if (res.confirm) {
          this.setData({ submitting: true });
          
          try {
            const result = await quitPublish(this.data.id);
            
            if (result.status === 200 || result.code === 200) {
              this.setData({ isParticipated: false });
              wx.showToast({
                title: '已退出拼单',
                icon: 'success'
              });
              // 重新加载详情以获取最新参与状态
              this.loadDetail();
            } else {
              wx.showToast({
                title: result.msg || '退出失败',
                icon: 'none'
              });
            }
          } catch (error: any) {
            console.error('退出拼单失败:', error);
            wx.showToast({
              title: typeof(error) === 'string' ? error : (error?.msg || '退出失败，请重试'),
              icon: 'none'
            });
          } finally {
            this.setData({ submitting: false });
          }
        }
      }
    });
  },

  // 分享
  onShareAppMessage() {
    return {
      title: this.data.detail ? `${this.data.detail.product_name} - 拼单` : '拼单详情',
      path: `/pages/group-detail/group-detail?id=${this.data.id}`
    };
  }
});
